package org.amos.server.utils;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.amos.core.basic.base.BaseEntity;
import org.amos.core.basic.constant.SystemConstant;
import org.amos.core.basic.utils.AmosUtils;
import org.amos.core.basic.utils.SpringUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

import static org.amos.core.basic.constant.SystemConstant.SYS_PARENT_ID_NAME;

/**
 * 系统树类工具类
 *
 * @author admin
 */
@Component
public class SysTreeUtils<T extends BaseEntity> {

    /**
     * 获取元素子集id集合
     *
     * @param id
     * @param childIds
     * @return
     */
    public List<Long> getChildrenIds(Long id, List<Long> childIds, Class<? extends BaseMapper<T>> clazz) {
        if (ObjectUtil.isEmpty(id)) {
            return new ArrayList<>();
        }
        QueryWrapper<T> qw = new QueryWrapper<>();
        qw.eq(SYS_PARENT_ID_NAME, id).eq(AmosUtils.toDbField(BaseEntity::getIsDeleted), SystemConstant.SYS_DELETE_FLAG_DEFAULT);
        List<T> list = SpringUtils.getBean(clazz).selectList(qw);
        list.forEach(x -> {
            childIds.add(x.getId());
            getChildrenIds(x.getId(), childIds, clazz);
        });
        return childIds;
    }
}
